package com.zhou.combine.security;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * <p>
 * mysql 代码生成器演示例子
 * </p>
 *
 * @author jobob
 * @since 2018-09-12
 */
public class MysqlGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * RUN THIS
     */
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/security-normal/src/main/java");
        gc.setAuthor("zhouxianfeng");
        gc.setOpen(false);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        /**
         * spring.datasource.url=jdbc:mysql://10.101.71.42:3306/dashboard_job?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&useOldAliasMetadataBehavior=true&allowMultiQueries=true
         * spring.datasource.username=root
         * spring.datasource.password=hd123456
         *
         * jdbc:mysql://10.101.71.41:3306/buried?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&useOldAliasMetadataBehavior=true&allowMultiQueries=true
         * com.mysql.jdbc.Driver
         * root
         * hd123456
         *
         */
        DataSourceConfig dsc = new DataSourceConfig();
        /*dsc.setUrl("jdbc:postgresql://10.101.70.169:5432/hdsc_db?currentSchema=bigdata");
        dsc.setSchemaName("bigdata");
        dsc.setDriverName("org.postgresql.Driver");
        dsc.setUsername("hdsc_bigdata_read");
        dsc.setPassword("84AiCeqLiyAWOiVz");
        dsc.setDbType(DbType.POSTGRE_SQL);*/
        dsc.setUrl("jdbc:mysql://10.101.71.41:3306/zhou_sonar?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&useOldAliasMetadataBehavior=true&allowMultiQueries=true");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("hd123456");
        dsc.setDbType(DbType.MYSQL);
        /**
         * //数据库类型 枚举
         *         dataSourceConfig.setDbType(DbType.SQL_SERVER)
         *                 //设置url
         *                 .setUrl(dbUrl)
         *                 //设置用户名
         *                 .setUsername("")
         *                 //设置密码
         *                 .setPassword("")
         *                 //设置数据库驱动
         *                 .setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
         *                 // 自定义数据库表字段类型转换【可选】
         *                 .setTypeConvert(new MySqlTypeConvert() {
         *                     @Override
         *                     public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
         *                         System.out.println("转换类型：" + fieldType);
         *                         //tinyint转换成Boolean
         *                          if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
         *                             return DbColumnType.BOOLEAN;
         *                          }
         *                          //将数据库中datetime转换成date
         *                         if ( fieldType.toLowerCase().contains( "datetime" ) ) {
         *                             return DbColumnType.DATE;
         *                         }
         *                         return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
         *                     }
         *                 });
         */
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //多模块时启用
        //pc.setModuleName(scanner("模块名"));
        pc.setParent("com.zhou.combine.security");
        mpg.setPackageInfo(pc);

        // 自定义配置
        List<FileOutConfig> focList = new ArrayList<>();

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        cfg.setFileCreate((configBuilder, fileType, filePath) -> {
            //如果是Entity则直接返回true表示写文件
            if (fileType == FileType.ENTITY) {
                return true;
            }
            //否则先判断文件是否存在
            File file = new File(filePath);
            boolean exist = file.exists();
            if (!exist) {
                file.getParentFile().mkdirs();
            }
            //文件不存在或者全局配置的fileOverride为true才写文件
            return !exist || configBuilder.getGlobalConfig().isFileOverride();
        });



        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + "/security-normal/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);
        //strategy.setSuperEntityClass("com.baomidou.mybatisplus.samples.generator.common.BaseEntity");
        strategy.setEntityLombokModel(true);
        //strategy.setSuperControllerClass("com.baomidou.mybatisplus.samples.generator.common.BaseController");
        strategy.setInclude(scanner("表名"));
        //strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");

        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}
